import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { App as AntdApp } from 'antd';

import { GetWorkBenhList } from '@/common/types';
import WorkbenchAll from '@/pages/workbench/components/workbenchAll';

import TgNavMenu from './TgNavMenu';
import TgNavTop from './TgNavTop';
import { isTiangongUser } from './utils/permissionUtils';

// 提供与工作台一致的数据结构以驱动 WorkBox
const buildMockApps = (): GetWorkBenhList[] => [
  {
    app_id: 'test-1',
    app_name: '测试智能体',
    app_type: 'agent',
    app_description: '这是一个测试智能体应用',
    app_logo: 'https://api.dicebear.com/7.x/initials/svg?seed=A',
    group_name: '测试组',
    user_name: '测试用户',
    create_time: '2023-10-26 10:00:00',
    review_time: '2023-10-26 10:00:00',
    review_result: 'pass',
    review_description: '',
    configurations: [],
    roles_for_user_in_app: ['admin'],
    review_status: 'pass',
    app_template_type: 'custom',
    app_workbench_type: 'manager',
    templateUsageCount: 0,
    templateThumbUpCount: 0,
    templateThumbDownCount: 0,
    isCollect: false,
    share_id: 'test-share-1',
    createUser: {
      groupId: 'test-group',
      groupName: '测试组',
      userId: 'test-user',
      userName: '测试用户',
    },
  },
  {
    app_id: 'test-2',
    app_name: '测试工作流',
    app_type: 'workflow',
    app_description: '这是一个测试工作流应用',
    app_logo: 'https://api.dicebear.com/7.x/initials/svg?seed=B',
    group_name: '测试组',
    user_name: '测试用户',
    create_time: '2023-10-25 15:30:00',
    review_time: '2023-10-25 15:30:00',
    review_result: 'pass',
    review_description: '',
    configurations: [],
    roles_for_user_in_app: ['admin'],
    review_status: 'pass',
    app_template_type: 'custom',
    app_workbench_type: 'manager',
    templateUsageCount: 0,
    templateThumbUpCount: 0,
    templateThumbDownCount: 0,
    isCollect: false,
    share_id: 'test-share-2',
    createUser: {
      groupId: 'test-group',
      groupName: '测试组',
      userId: 'test-user',
      userName: '测试用户',
    },
  },
];

interface MenuItem {
  id: string;
  label: string;
  type: 'main' | 'sub' | 'toggle';
  active?: boolean;
  children?: MenuItem[];
}

interface UserInfo {
  username: string;
  name: string;
  loginTime: string;
  role?: {
    name: string;
    code: string;
    label: string;
  };
  dataVisibility?: {
    showAdvancedFeatures: boolean;
    showSensitiveData: boolean;
    showDebugInfo: boolean;
    showSystemLogs: boolean;
  };
  featurePermissions?: {
    canCreateApp: boolean;
    canManageWorkflow: boolean;
    canAccessAI: boolean;
    canManageKnowledge: boolean;
    canViewAnalytics: boolean;
    canExportData: boolean;
    canDeleteData: boolean;
    canManageUsers: boolean;
  };
}

const Index: React.FC = () => {
  const navigate = useNavigate();
  const [activeMenu, setActiveMenu] = useState('digital');
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);

  const menuItems: MenuItem[] = [
    {
      id: 'tiangong',
      label: '天工',
      type: 'main',
      children: [{ id: 'ruihe', label: '睿核', type: 'sub' }],
    },
    {
      id: 'digital',
      label: '数字员工',
      type: 'main',
    },
    { id: 'data', label: '数据', type: 'toggle', active: false },
    { id: 'insight', label: '洞察', type: 'toggle', active: false },
  ];

  const getLabelById = (id: string) => {
    const direct = menuItems.find((i) => i.id === id)?.label;
    if (direct) return direct;
    const withChildren = menuItems.find((i) => i.children && i.children.some((c) => c.id === id));
    const child = withChildren?.children?.find((c) => c.id === id);
    return child?.label || '数据';
  };

  // 根据用户权限过滤菜单项
  const getFilteredMenuItems = () => {
    if (!userInfo || !isTiangongUser(userInfo)) return menuItems;

    return menuItems.map((item) => {
      switch (item.id) {
        case 'data':
          return {
            ...item,
            active: userInfo.featurePermissions?.canViewAnalytics ?? false,
          };
        case 'insight':
          return {
            ...item,
            active: userInfo.featurePermissions?.canViewAnalytics ?? false,
          };
        default:
          return item;
      }
    });
  };

  const handleMenuClick = (itemId: string) => {
    setActiveMenu(itemId);
  };

  useEffect(() => {
    const userData = localStorage.getItem('tiangong_user');
    if (userData) {
      setUserInfo(JSON.parse(userData));
    } else {
      navigate('/tiangong-ai/login');
    }
  }, [navigate]);

  const handleLogout = () => {
    localStorage.removeItem('tiangong_user');
    navigate('/tiangong-ai/login');
  };

  return (
    <AntdApp>
      <div style={{ display: 'flex', height: '100vh', background: '#f5f5f5' }}>
        {/* 左侧菜单 */}
        <TgNavMenu
          activeKey={activeMenu}
          menuItems={getFilteredMenuItems()}
          onMenuClick={handleMenuClick}
        />

        {/* 主内容区域 */}
        <div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
          {/* 顶部导航 */}
          <TgNavTop
            title={getLabelById(activeMenu)}
            isActive
            userInfo={userInfo}
            onLogout={handleLogout}
          />

          {/* 主内容区域 */}
          <div style={{ flex: 1, overflow: 'auto', padding: 16 }}>
            {activeMenu === 'digital' ? (
              <WorkbenchAll
                name={'1'}
                appList={buildMockApps()}
                isNoData={false}
                isLoading={false}
                flag={false}
                height={0}
              />
            ) : (
              <div style={{ background: '#fff', padding: 16, borderRadius: 8 }}>
                <h3>{getLabelById(activeMenu)}</h3>
                <p>这里是 {getLabelById(activeMenu)} 页面的内容</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </AntdApp>
  );
};

export default Index;
